/**
 * Sample React Native App
 * https://github.com/facebook/react-native
 *
 * @format
 * @flow
 */

import React, { Component } from "react";
import { StatusBar, StyleSheet, View } from "react-native";
import { Provider } from "react-redux";
import * as wechat from "react-native-wechat";
import { ActionSheetProvider } from "@expo/react-native-action-sheet";
import configureStore from "./store/ConfigureStore";
import NavigatorUtil from "./utils/NavigatorUtil";
import StorageUtil from "./utils/StorageUtil";
import App from "./Stack";
import { Color, isIOS } from "./common/index";

const store = configureStore();

export default class Root extends Component {
  componentDidMount() {
    wechat.registerApp("wx58a330129e225f3c");
    StorageUtil.loadToken();
    // StorageUtil.saveUserTest();
  }

  getCurrentRouteName(navigationState) {
    if (!navigationState) {
      return null;
    }
    const route = navigationState.routes[navigationState.index];
    // dive into nested navigators
    if (route.routes) {
      return this.getCurrentRouteName(route);
    }
    return route.routeName;
  }

  handleNavigationChange = (prevState, currentState) => {
    const currentScreen = this.getCurrentRouteName(currentState);
    const prevScreen = this.getCurrentRouteName(prevState);
    if (prevScreen !== currentScreen) {
      if (currentScreen === "Mine" || currentScreen === "Recycle") {
        StatusBar.setBarStyle("light-content");
        !isIOS && StatusBar.setBackgroundColor(Color.tab_yellow);
      } else if (currentScreen === "FirstLunch") {
        StatusBar.setBarStyle("light-content");
        !isIOS && StatusBar.setBackgroundColor("#3788C9");
      } else {
        StatusBar.setBarStyle("dark-content");
        !isIOS && StatusBar.setBackgroundColor(Color.bg_tabbar);
      }
    }
  };

  render() {
    const { routerKey, routerParam } = this.props;

    return (
      <View style={styles.container}>
        <StatusBar backgroundColor="#3788C9" barStyle="dark-content" />
        <Provider store={store}>
          <ActionSheetProvider>
            <App
              ref={nav => {
                NavigatorUtil.setTopLevelNavigator(nav);
              }}
              onNavigationStateChange={this.handleNavigationChange}
              screenProps={{
                routerKey,
                routerParam,
                props: this.props,
              }}
            />
          </ActionSheetProvider>
        </Provider>
      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: "#F5FCFF",
  },
});
